package com.kabuda.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.kabuda.blog.dao.pojo.SysUser;
import com.kabuda.blog.service.RegisterService;
import com.kabuda.blog.service.SysUserService;
import com.kabuda.blog.utils.JWTUtils;
import com.kabuda.blog.vo.ErrorCode;
import com.kabuda.blog.vo.Result;
import com.kabuda.blog.vo.params.LoginParams;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author kabuda
 * @create 2023-01-17 14:06
 */
@Service
@Transactional
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;



    @Override
    public Result register(LoginParams loginParams) {
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        String nickname = loginParams.getNickname();
        //1.参数判空
        if(!StringUtils.hasText(account)||!StringUtils.hasText(password)||!StringUtils.hasText(nickname)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }

        //2.查询账号在数据库是否存在
        boolean isNotEXIST=sysUserService.findUserByAccount(account);
        SysUser sysUser = new SysUser();
        if(isNotEXIST){
            //不存在，可以插入
            sysUser.setNickname(nickname);
            sysUser.setAccount(account);
            String passwordMD5 = Md5Crypt.md5Crypt(password.getBytes(), LoginServiceImpl.slat);
            sysUser.setPassword(passwordMD5);
            sysUser.setCreateDate(System.currentTimeMillis());
            sysUser.setLastLogin(System.currentTimeMillis());
            sysUser.setAvatar("/static/img/logo.png");
            sysUser.setAdmin(1); //1 为true
            sysUser.setDeleted(0); // 0 为false
            sysUser.setSalt("");
            sysUser.setStatus("");
            sysUser.setEmail("");
            sysUserService.saveUser(sysUser);
        }else{
            return Result.fail(ErrorCode.Account_EXIST.getCode(),ErrorCode.Account_EXIST.getMsg());
        }

        //3.获取token返回给前端
        String token = JWTUtils.createToken(sysUser.getId());

        //4.redis存储token
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);

        return Result.success(token);


    }
}
